﻿using Cartographer.Extensions;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Xml.Linq;

namespace Cartographer.Tiled
{
	public class TiledData
	{
		public string Encoding { get; set; }
		public string Compression { get; set; }
		public string Data { get; set; }
		public List<UInt32> TileIndicies { get; set; }

		public TiledData() { }

		public TiledData(XElement element)
		{
			Encoding = element.GetAttribute<string>("encoding");
			Compression = element.GetAttribute<string>("compression");
			Data = element.Value.Trim();

			TileIndicies = new List<UInt32>();

			if (Encoding == "base64")
			{
				var data = Convert.FromBase64String(Data);
				using (var stream = new MemoryStream(data))
				{
					stream.ReadByte();
					stream.ReadByte();
					var deflateStream = new DeflateStream(stream, CompressionMode.Decompress);
					var buffer = new byte[sizeof(UInt32)];
					while (deflateStream.Read(buffer, 0, buffer.Length) == buffer.Length)
					{
						TileIndicies.Add(BitConverter.ToUInt32(buffer, 0));
					}
				}
			}
		}
	}
}